#!/usr/bin/bash


authselect check &> /dev/null && auCheck=0

if [[ $auCheck == "0" ]] ; then
    customProfile=$(authselect current | awk 'NR == 1 {print $3}' | grep custom/)
    currProfile=$(authselect current | awk 'NR == 1 {print $3}')
    createP="user-profile"

    # 判断是否已有用户自定义规则集，如有则跳过创建步骤，改为直接追加已有的规则集
    if [[ -z $customProfile ]]; then
        authselect create-profile $createP -b $currProfile
        authselect select custom/$createP
        authselect apply-changes
    fi
fi

[[ $auCheck == "0" ]] && customProfile=$(authselect current | awk 'NR == 1 {print $3}' | grep custom/) || customProfile=""
# 判断是否有自定义规则集，如没有或创建失败，则直接对最终文件(/etc/pam.d/password-auth,/etc/pam.d/system-auth)进行修改
for FN in system-auth password-auth; do
    [[ -n $customProfile ]] && PTF=/etc/authselect/$customProfile/$FN || PTF=/etc/pam.d/$FN
    [[ -z $(grep -E '^\s*auth\s+required\s+pam_faillock.so.*$' $PTF) ]] && ln=$(grep -En -m1 '^\s*auth\s+' $PTF | cut -d: -f1) && sed -i "${ln}i\auth    required    pam_faillock.so    preauth silent \nauth    required    pam_faillock.so    authfail " $PTF

    denyLN=$(grep -En '^\s*auth\s+required\s+pam_faillock.so\s*.*' $PTF | grep -Pv "deny=" | cut -d: -f1)
    if [[ -n $denyLN ]] ; then
        for l in $denyLN; do sed -ri "${l}s/^\s*(auth\s+required\s+pam_faillock\.so\s+)(.*)$/\1\2 deny=5 /" $PTF ; done
    elif [[ -n $(grep -E '^\s*auth\s+required\s+pam_faillock.so\s*.*deny=\S+\s*.*$' $PTF) ]] ;then
        sed -ri "/pam_faillock.so/s/deny=\S+/deny=5/g" $PTF
    fi

    unlockLN=$(grep -En '^\s*auth\s+required\s+pam_faillock.so\s*.*' $PTF | grep -Pv "unlock_time=" | cut -d: -f1)
    if [[ -n $unlockLN ]] ; then
        for l in $unlockLN; do sed -ri "${l}s/^\s*(auth\s+required\s+pam_faillock\.so\s+)(.*)$/\1\2 unlock_time=900 /g" $PTF ; done
    elif [[ -n $(grep -E '^\s*auth\s+required\s+pam_faillock.so\s*.*unlock_time=\S+\s*.*$' $PTF) ]] ;then
        sed -ri '/pam_faillock.so/s/unlock_time=\S+/unlock_time=900/g' $PTF
    fi
done

[[ $auCheck == "0" ]] && authselect apply-changes &> /dev/null
# 启用faillock模块
[[ $auCheck == "0" ]] && authselect enable-feature with-faillock &> /dev/null